package com.twu.biblioteca;

import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

@Component
public class Authorizer {

    private final LibraryId libraryId;
    private final Map <String,User> users;
    private boolean isUserLoggedIn = false;
    private User loggedUser;

    @Inject
    public Authorizer(LibraryId libraryId) {
        this.libraryId = libraryId;
        this.users = new HashMap<>();
    }

    public boolean login(String username, String password) {
        User user = users.get(username);
        if (user != null && user.getPassword().equals(password)) {
            isUserLoggedIn = true;
            loggedUser = user;
            return true;
        }
        return false;
    }

    public void addUser(String password) throws LibraryIdOverflow {
        User user = new User(libraryId.generate(), password);
        users.put(user.getLibraryId(), user);
    }

    public boolean isUserLoggedIn() {
        return isUserLoggedIn;
    }

    public User getLoggedUser() {
        return loggedUser;
    }

    public Map<String,User> getUsers() {
        return users;
    }
}
